package com.mec.web.y2012.ajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mec.beans.y2012.ajax.NameService;

/**
 * Servlet implementation class AutoCompleteServlet
 */
@WebServlet("/ajax/autoComplete")
public class AutoCompleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private List<String> names = new ArrayList<String>();
    
    public AutoCompleteServlet() {
        super();
    }

    
	@Override
	public void init() throws ServletException {
		super.init();
		names.add("Abe");
		names.add("Abel");
		names.add("Abigail");
		names.add("Abner");
		names.add("Abraham");
		names.add("Marcus");
		names.add("Marcy");
		names.add("Marge");
		names.add("Marie");
	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String prefix = request.getParameter("names");
		
		NameService service = NameService.getInstance(names);
		List<String> matching = service.findNames(prefix);
		
		//
		if(matching.isEmpty()){
			response.setStatus(HttpServletResponse.SC_NO_CONTENT);
			return;
		}
			
		PrintWriter out = response.getWriter();
		
		response.setContentType("text/xml");
		response.setHeader("Cache-Control", "no-cache");
		
		out.println("<response>");
		
		for(String name : matching){
			out.println("<name>" + name + "</name>");
		}
		
		out.println("</response>");
		
		matching = null;
		service = null;
		out.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private static final Logger logger = 
			Logger.getLogger(AutoCompleteServlet.class);

}
